package com.tangdi.production.mpaychl.controller.third;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;
import com.tangdi.production.mpaychl.controller.BaseController;
import com.tangdi.production.mpaychl.service.impl.getway.GetWayServiceImpl;
import com.tangdi.production.mpbase.constants.ExcepCode;
import com.tangdi.production.mpbase.constants.MsgCT;
import com.tangdi.production.mpbase.exception.BusinessException;
import com.tangdi.production.mpbase.service.OrderService;
import com.tangdi.production.mpbase.util.MoneyUtils;

@Controller
@RequestMapping("getway")
public class GetWayController extends BaseController{
	private static Logger logger = LoggerFactory.getLogger(BailipayController.class);
	
	@Autowired
	private OrderService orderService;
	
	@RequestMapping(value={"/notify-url"},method={RequestMethod.POST,RequestMethod.GET})
	public void notifyUrl(HttpServletRequest request, HttpServletResponse response){
		logger.info("getway异步回调开始");
		
        // 将异步通知中收到的所有参数都存放到map中
        Map<String, Object> paramsMap = getRequestParamsV2(request);
        logger.info("异步回调,获取getway异步返回,参数:{}", paramsMap);
        
        try {
            // 签名
            String merOrderId = (String) paramsMap.get("merOrderId");
            String merchantId = (String) paramsMap.get("merchantId");
            String code = (String) paramsMap.get("code");
            String transAmt = (String) paramsMap.get("transAmt");
            String msg = (String) paramsMap.get("msg");
            String transTime = (String) paramsMap.get("transTime");
            String sign = (String) paramsMap.get("sign");
        	
            paramsMap.remove("sign");
            String signValue = sign(paramsMap, GetWayServiceImpl.SIGNKEY);

            logger.info("返回签名:{}, 生成签名:{}", sign, signValue);
            if (sign.equals(signValue)){
                if("00".equals(code)){
                    //支付成功，写返回数据逻辑
                	logger.info("验签成功,签名:{}", signValue);
                    respContent(response, "success");
                }else{
                    logger.error("支付失败");
                    returnFailure(response);
                    return;
                }
            }else{
                logger.error("验签失败");
                returnFailure(response);
                return;
            }
            
      /*      if(!"00".equals(code)){
                //支付成功，写返回数据逻辑
            	returnFailure(response);
                return;
            } else {
                //支付成功，写返回数据逻辑
            	logger.info("没有验签，但是返回code为成功，暂时算做成功");
                respContent(response, "success");
            }*/
            
			// 订单号
			String prdOrdNo = merOrderId;
			if(StringUtils.isEmpty(prdOrdNo)){
				throw new BusinessException(ExcepCode.EX900000,"回调订单号为空");
			}
			
			Map<String,Object> queryMap = new HashMap<String,Object>();
			queryMap.put("prdOrdNo", prdOrdNo);
			Map<String,Object> prdOrdMap = orderService.getPrdOrdMap(queryMap);
			
			String ordStatus = (String) prdOrdMap.get("ordStatus");
			if(MsgCT.ORDSTATUS_SUCCESS.equals(ordStatus)){//成功的订单不允许再更新
				logger.warn("订单状态已成功，不允许更新...");
				returnSuccess(response);
				return;
			}
			
			logger.info("支付订单金额[{}]元", transAmt);
			String ovalue = MoneyUtils.toStrCent(transAmt);
			if(ovalue.equals(prdOrdMap.get("txAmt").toString()) == false){
				throw new BusinessException(ExcepCode.EX900000,"支付金额不一致 成功金额[{}] 订单支付金额[{}]",ovalue, prdOrdMap.get("txAmt").toString());
			}
			
			//原交易大商户编号
			String mchNo = (String)prdOrdMap.get("TMERCID");
			if(StringUtils.isEmpty(mchNo)){
				throw new BusinessException(ExcepCode.EX900000,"原交易商户号不能为空");
			}
			
			//定义回调订单信息Map
			Map<String,Object> orderCallBackMap = new HashMap<String, Object>();
			orderCallBackMap.put("prdOrdNo", prdOrdMap.get("prdOrdNo"));//订单号
			orderCallBackMap.put("ordStatus", MsgCT.ORDSTATUS_PROCESSING);
			orderCallBackMap.put("resJson", JSON.toJSONString(paramsMap));
			
			//支付成功
			orderCallBackMap.put("ordStatus", MsgCT.ORDSTATUS_SUCCESS);
			
			//调用回调更新订单
			logger.info("通知平台更新订单[{}]",orderCallBackMap);
			orderService.prdPayCallBack(orderCallBackMap);
			
            // 处理成功后，需要返回SUCCESS，通知中心接受到SUCCESS后将不再通知
            returnSuccess(response);
        	
        } catch (Exception e){
        	logger.error("getway异步通知失败:{}", e.getMessage(), e);
        }

		logger.info("getway异步回调完成");
	}
}
